{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Python len built-in-function.ipynb",
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/Tanu-N-Prabhu/Python/blob/master/Python_len()_built_in_function.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VeW4LbNhl3CE",
        "colab_type": "text"
      },
      "source": [
        "# Learn the Python len() Function\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ud7txvqml4Fa",
        "colab_type": "text"
      },
      "source": [
        "## A detailed guide to the len() function in Python\n",
        "\n",
        "\n",
        "\n",
        "![alt text](https://miro.medium.com/max/1739/1*2X_GAl1ZRDPnxkteliwTUQ.png)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SgPZWfGRmNDF",
        "colab_type": "text"
      },
      "source": [
        "# Definition"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gXWuLaoEmbVr",
        "colab_type": "text"
      },
      "source": [
        "The `len()` Python function counts the number of items in an object. The object can be a string, tuple, dictionary, list, sets, array, and many more. The items here are the elements inside these objects, and the count represents the number of occurrences of these items in an object.\n",
        "\n",
        "\n",
        "\n",
        "---\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aWDsDALynDzj",
        "colab_type": "text"
      },
      "source": [
        "# Syntax\n",
        "The syntax of the `len()` function is:\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "```\n",
        "len(obj)\n",
        "```\n",
        "However, in the later versions of Python (ie. Python v3.5.1+) the syntax is:\n",
        "\n",
        "\n",
        "\n",
        "```\n",
        "len(obj, /)\n",
        "```\n",
        "\n",
        "\n",
        "The `/ `indicates Positional-Only-Arguments. Don’t worry about it too much because that itself is a different concept. I’ll follow up with an article detailing that further.\n",
        "\n",
        "\n",
        "\n",
        "---\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2x6dDKZnoAqZ",
        "colab_type": "text"
      },
      "source": [
        "# Arguments\n",
        "\n",
        "The `len()` function accepts exactly one argument. It does not take any keyword arguments. The argument should either be a sequence or a collection.\n",
        "\n",
        "\n",
        "\n",
        "> Failing to pass an argument or passing an invalid argument will raise a `TypeError` exception\n",
        "\n",
        "Now you might be wondering what a sequence or collection is.\n",
        "\n",
        "**Sequence**: A group of items with deterministic ordering, meaning the order doesn't change. When you add items, the order would be retained, and you get the same order of items in return. Examples of a sequence are → **strings, lists, tuples.**\n",
        "\n",
        "For example, consider a list comprising the following elements as shown below:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZwNyEjsroyvz",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "60d4f04e-d40d-4a60-a24e-c81f0fcce001"
      },
      "source": [
        "l = [3, 4, 2, 1]\n",
        "print(type(l))"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'list'>\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bId3supYo1gz",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "45127df1-4650-4c67-f01c-5e81fcc2f976"
      },
      "source": [
        "print(l)"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[3, 4, 2, 1]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e88Rv-KLo4Kh",
        "colab_type": "text"
      },
      "source": [
        "The order did not change in a sequence. This is what meant by deterministic order.\n",
        "\n",
        "**Collections**: Unlike sequences, the collection has no deterministic ordering. Here, the order of items changes accordingly. Examples of collections are → **Sets and Dictionaries**.\n",
        "\n",
        "Consider the below example of a set with the following elements:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lPylIcHjo8h2",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "c2c9034f-125b-47c0-badc-36ac93e077e6"
      },
      "source": [
        "s = set([3, 4, 2, 1])\n",
        "print(type(s))"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'set'>\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GF9IeZmio9_U",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "63c5d208-ec1b-4b05-b896-c6426b330462"
      },
      "source": [
        "print(s)"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "{1, 2, 3, 4}\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Wc6zmlDvpAvl",
        "colab_type": "text"
      },
      "source": [
        "As seen above, the set function changed the order of the items. This is one of the main advantages of collections.\n",
        "\n",
        "Below is the clear chart which comprises examples of sequences and collections:\n",
        "\n",
        "\n",
        "![alt text](https://miro.medium.com/max/1800/1*LsZUvZ92hhOj1dpE9qZm7g.jpeg)\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "---\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KCRuTR-OpLCw",
        "colab_type": "text"
      },
      "source": [
        "# Return Type\n",
        "\n",
        "The `len(`) function returns the number of items in a container. For example, consider the container here to be a string of elements. In this case, `len()` returns the ***number of characters*** in the string.\n",
        "\n",
        "\n",
        "\n",
        "---\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lFgJp-3ApS4s",
        "colab_type": "text"
      },
      "source": [
        "# Examples and Usage\n",
        "\n",
        "Below are examples and the usage of the `len()` function with different objects such as string, list, sets, tuple, and dictionary.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "w68EPcYtpW6b",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "f5536076-2af7-44a6-9ef8-3f0da19235ab"
      },
      "source": [
        "str = \"Programming\"       # String\n",
        "print(type(str))\n",
        "print(len(str))"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'str'>\n",
            "11\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "MpsGx20PpaH2",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "6e5a53ea-3263-450b-9cd9-1ef4e6ca5b86"
      },
      "source": [
        "l = [1, 2, 3, 4, 5]       # List\n",
        "print(type(l)) \n",
        "print(len(l))"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'list'>\n",
            "5\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "QMC6KmKcpbvh",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "ec8009c6-2682-4402-c440-ce80c50be977"
      },
      "source": [
        "set = {\"Python\", \"Programming\", \"Is\", \"Fun\"}     # Set\n",
        "print(type(set))\n",
        "print(len(set))"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'set'>\n",
            "4\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "grzFwbb3pdet",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "40fc8c9f-a5a7-47f4-a867-c477be50f4bc"
      },
      "source": [
        "tup = (\"Coding\", \"Is\", \"Easy\")                   # Tuple\n",
        "print(type(tup))\n",
        "print(len(tup))"
      ],
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'tuple'>\n",
            "3\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SK7aLWlTpfDO",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "fd6bc266-15bc-43c6-df9c-1047c682ca91"
      },
      "source": [
        "dict = {\"Learn\": 1, \"To\": 2, \"Code\": 3}         # Dictionary\n",
        "print(type(dict))\n",
        "print(len(dict))"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'dict'>\n",
            "3\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Fg0J9ZufphKZ",
        "colab_type": "text"
      },
      "source": [
        "`len()` does not work with integer values and the iterator values. Consider the below example:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1oVhk89bpjmW",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 201
        },
        "outputId": "20035e6b-059f-41e5-c955-4d821e447462"
      },
      "source": [
        "def value():\n",
        "    a = 25    # Integer value\n",
        "    return a\n",
        "print(len(value()))"
      ],
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "error",
          "ename": "TypeError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-10-b2b553c71dc7>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      2\u001b[0m     \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m25\u001b[0m    \u001b[0;31m# Integer value\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m     \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m: object of type 'int' has no len()"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "64K9cbX1plwf",
        "colab_type": "text"
      },
      "source": [
        "It also fails to work on iterators using ***for looping statements***. Try it, I’m not joking."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MSU-_PT2pqPg",
        "colab_type": "text"
      },
      "source": [
        "On converting the above example from integer to the string, `len()` works completely fine."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qikOabAhptve",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "4a0c8d7c-237c-4103-c9ed-ee8f9e97fc3e"
      },
      "source": [
        "def value():\n",
        "    a = \"25\"    # String value\n",
        "    print(type(a))\n",
        "    return a\n",
        "print(len(value()))"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'str'>\n",
            "2\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SnqpAeoGpwt5",
        "colab_type": "text"
      },
      "source": [
        "See I told you, there was no problem when the value is of ***string*** type. If anybody of you guys knows the answer let me know, I am curious.\n",
        "\n",
        "\n",
        "\n",
        "---\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZPbWdOdyp0rr",
        "colab_type": "text"
      },
      "source": [
        "This is a small article with a lot to learn about the `len()` function. Stay tuned for more updates. I hope you enjoyed reading the article. If you have any doubts regarding the content, then the comment section is all yours. Thank you guys for spending your precious time reading my article. Until then, Goodbye.\n",
        "\n",
        "\n",
        "# Author: Tanu Nanda Prabhu"
      ]
    }
  ]
}